//
//  EDTodayGamesVC.m
//  EDF
//
//  Created by 微笑吧阳光 on 2019/7/26.
//  Copyright © 2019 p. All rights reserved.
//

#import "EDTodayGamesVC.h"
#import "EDRichTextLabel.h"
#import "TwoBtnsView.h"
#import "LLWebViewController.h"

#define Start_X          30.0f      // 第一个按钮的X坐标
#define Start_Y          15.0f     // 第一个按钮的Y坐标
#define Width_Space      15.0f      // 2个按钮之间的横间距
#define Height_Space     15.0f     // 竖间距
#define Button_Height   35.0f    // 高
#define Button_Width    75.0f    // 宽

@interface EDTodayGamesVC ()
@property(nonatomic,strong)UIScrollView * bgSc;
@property(nonatomic,strong)   UILabel * topLab;
@property(nonatomic,strong)   UILabel * topLab2;
@property(nonatomic,strong)   UIImageView * topImageV;
@property(nonatomic,strong)   NSDictionary * gameInfoDicc;
@property(nonatomic,strong)   UIView * btnsView;

@end

@implementation EDTodayGamesVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.gameInfoDicc = [NSDictionary dictionary];
    [self creatUI];
  
    WEAKSELF
        self.bgSc.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            //调用刷新方法
            STRONGSELFFor(weakSelf);
            [strongSelf getGameInfo];
        }];
        [self.bgSc.mj_header beginRefreshing];
}
-(void)getGameInfo{
    //Game_loadDailyGamePromotion
    [self showLoadingAnimation];
    NSString  * balance = [[YINetWorkAPIGenerate sharedInstance] APINomark:@"Game_loadDailyGamePromotion"];
    WEAKSELF
    [[SmileHttpTool sharedInstance] GET :balance parameters:nil origin:YES success:^(NSInteger statusCode, NSString *message, id responseObject) {
        [self stopLoadingAnimation];
        STRONGSELFFor(weakSelf);
        //NSLog(@"User_getActivityAll---%@",responseObject);
        NSError *errorData;
        NSData * data =[responseObject dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&errorData];
        

        if ([[dict jsonString:@"statusCode"] isEqualToString:@"SUCCESS"]) {
            NSDictionary * dataDicc = [dict jsonDict:@"data"];
            YYLog(@"Game_loadDailyGamePromotion---%@",dict);
            //PTimageGameURL
        
            dispatch_async(dispatch_get_main_queue(), ^{
                      self.gameInfoDicc  = [NSDictionary dictionaryWithDictionary:dataDicc];
                NSArray * datdArry = [dataDicc jsonArray:@"bonus_list"];
            [strongSelf creatBtnsView:datdArry];

           [strongSelf.topImageV sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",PTimageGameURL,[dataDicc jsonString:@"game_pic"]]] placeholderImage:coverPlaceholder];

                NSString *HTMLString = [NSString stringWithFormat:@"<html><body><p>%@</p></body></html>", [dataDicc jsonString:@"tips_txt"] ];
                
                NSDictionary *options = @{NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType,
                                          NSCharacterEncodingDocumentAttribute : @(NSUTF8StringEncoding)
                                          };
                NSData *data = [HTMLString dataUsingEncoding:NSUTF8StringEncoding];
                
                NSMutableAttributedString * attributedString = [[NSMutableAttributedString alloc] initWithData:data options:options documentAttributes:nil error:nil];
                
                NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];   // 调整行间距
                paragraphStyle.lineSpacing = 1.0;
                paragraphStyle.alignment = NSTextAlignmentCenter;
                [attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, attributedString.length)];
                [attributedString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:14] range:NSMakeRange(0, attributedString.length)];
                self.topLab2.attributedText = attributedString;
                self.topLab2.textAlignment =NSTextAlignmentCenter;
               // self.topLab2.textColor = kRGBColor(68, 68, 68);
                
                
                
               // [strongSelf.topLab sizeToFit];

            });
        }else{
            dispatch_async(dispatch_get_main_queue(), ^{
                ToastView * toast = [[ToastView alloc] initWithtToastandStayTime:1 andImageName:@"error" andTitleStr:[dict jsonString:@"message"] andlightStr:@""];
                [toast showLXAlertView];
            });
        }
        [self.bgSc.mj_header endRefreshing];
    } failure:^(id responseObject, NSError *error) {
        [self stopLoadingAnimation];
        [self.bgSc.mj_header endRefreshing];
        [WJUnit showMessage:@"请求失败"];
        //[self getBalance];
        
    }];
}
-(void)creatBtnsView:(NSArray *)btnsArry{
    
    
    self.modelsArry = [NSMutableArray arrayWithArray:btnsArry];
    [self.btnsView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    
    CGFloat  btnW = (kScreenWidth-75)/2;
    
    for (int i = 0 ; i < btnsArry.count; i++) {
        NSDictionary * dicc = [btnsArry objectAtIndex:i ];
        NSInteger index = i % 2;
        NSInteger page = i / 2;
        // 圆角按钮
        UIButton *mapBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        mapBtn.tag = i;//这句话不写等于废了
        mapBtn.frame = CGRectMake(index * (btnW + Width_Space) + Start_X, page  * (Button_Height + Height_Space)+Start_Y, btnW, Button_Height);
        if (i ==0) {
            [mapBtn setTitle:[NSString stringWithFormat:@"申请%@发币",[dicc jsonString:@"bonus"]] forState:0];
        }else{
               [mapBtn setTitle:[NSString stringWithFormat:@"申请%@彩金",[dicc jsonString:@"bonus"]] forState:0];
        }
       
        [mapBtn setTitleColor:[UIColor whiteColor] forState:0];
        KViewRadius(mapBtn, 4);
        if ([[dicc jsonString:@"status"] isEqualToString:@"valid"]) {
            [mapBtn setBackgroundColor:kRGBColor(44, 143, 219) forState:0];
            mapBtn.enabled = YES;
        }else if ([[dicc jsonString:@"status"] isEqualToString:@"invalid"]){
            [mapBtn setBackgroundColor:kRGBColor(161, 161, 161) forState:0];
            mapBtn.enabled = NO;
        }else{
            //finish
            [mapBtn setBackgroundColor:kRGBColor(161, 161, 161) forState:0];
            mapBtn.enabled = NO;
        }
        if (i==btnsArry.count-1) {
            
            self.topLab.text = [NSString stringWithFormat:@"今日投注 %@ 平台的”%@“，最高可获得%@元！",[self.gameInfoDicc jsonString:@"gameplat_name"],[self.gameInfoDicc jsonString:@"game_name"],[dicc jsonString:@"bonus"]];
            NSMutableAttributedString * strr1 =[NSAttributedString_Encapsulation changeAstringTextColorWithColor:EDColor_BaseBlue string:[NSString stringWithFormat:@"今日投注 %@ 平台的”%@“，最高可获得%@元！",[self.gameInfoDicc jsonString:@"gameplat_name"],[self.gameInfoDicc jsonString:@"game_name"],[dicc jsonString:@"bonus"]] andSubString:@[[self.gameInfoDicc jsonString:@"gameplat_name"],[self.gameInfoDicc jsonString:@"game_name"]] changeFontAndColor:[UIFont boldSystemFontOfSize:15] Color:kRGBColor(68, 68, 68) blodSubStringArray:@[] isCenter:YES];
            
            self.topLab.textAlignment = NSTextAlignmentCenter;
            self.topLab.numberOfLines = 0;
            self.topLab.textColor = kRGBColor(68, 68, 68);
            self.topLab.font = [UIFont systemFontOfSize:15];
            self.topLab.attributedText = strr1;
        }
        [mapBtn addTarget:self action:@selector(mapBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [self.btnsView addSubview:mapBtn];
        
    }
    
    
}
-(void)mapBtnClick:(UIButton*)sender{
    
    //Game_onGetDailyGameBonus
    [self showLoadingAnimation];
     NSDictionary * dicc = self.modelsArry[sender.tag];
    NSString  * url = [[YINetWorkAPIGenerate sharedInstance] APINomark:@"Game_onGetDailyGameBonus"];
    NSMutableDictionary * jsonDicc = [NSMutableDictionary dictionary];
    [jsonDicc setValue:[self.gameInfoDicc jsonString:@"geid"] forKey:@"geid"];
     [jsonDicc setValue:[dicc jsonString:@"bet"] forKey:@"betLineStr"];
    WEAKSELF
    [[SmileHttpTool sharedInstance] GET :url parameters:jsonDicc origin:YES success:^(NSInteger statusCode, NSString *message, id responseObject) {
        [self stopLoadingAnimation];
        STRONGSELFFor(weakSelf)
        NSError *errorData;
        NSData * data =[responseObject dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
        NSDictionary *dict001 = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&errorData];
        NSString *responseObjectStr =[dict001 jsonString:@"statusCode"];
        if ([responseObjectStr isEqualToString:@"SUCCESS"]) {
            YYLog(@"loadDailySignPromotion----%@",dict001);
            dispatch_async(dispatch_get_main_queue(), ^{
                ToastView * toast = [[ToastView alloc] initWithtToastandStayTime:1 andImageName:@"success" andTitleStr:[dict001 jsonString:@"data"] andlightStr:@""];
                [toast showLXAlertView];
                [sender setBackgroundColor:kRGBColor(161, 161, 161) forState:0];
                sender.enabled = NO;
                [self getGameInfo];
            });
        }else{
            dispatch_async(dispatch_get_main_queue(), ^{
                ToastView * toast = [[ToastView alloc] initWithtToastandStayTime:1 andImageName:@"error" andTitleStr:[dict001 jsonString:@"message"] andlightStr:@""];
                [toast showLXAlertView];
            });
        }
    } failure:^(id responseObject, NSError *error) {
        [self stopLoadingAnimation];
        NSLog(@"error----%@",error);
        [JMNotifyView showNotify:@"网络错误，请重试~" isSuccessful:NO];
    }];
    
    
    
    
}
-(void)creatUI{
    self.bgSc = [[UIScrollView alloc]init];
    self.bgSc.frame = CGRectMake(0, kStatusBarAndNavigationBarHeight, kScreenWidth, kScreenHeight-kStatusBarAndNavigationBarHeight);
    self.bgSc.backgroundColor = kRGBColor(245, 245, 245);
    [self.view addSubview:self.bgSc];
    
   self.topLab = [BBControl createLabelWithFrame:CGRectMake(10, 15, kScreenWidth-20, 40) Font:16 Text:@"今日投注"];
    self.topLab.backgroundColor = [UIColor clearColor];
    self.topLab.textAlignment = NSTextAlignmentCenter;
    [self.bgSc addSubview:self.topLab];
    self.topLab.textColor = kRGBColor(63, 63, 63);
    
    self.topImageV = [BBControl createImageViewFrame:CGRectMake(kScreenWidth/2-70, self.topLab.bottom, 140, 100) imageName:@""];
    [self.bgSc addSubview:self.topImageV];
    
    UIButton * enterbtn = [BBControl createButtonWithFrame:CGRectMake(50, self.topImageV.bottom+10, kScreenWidth-100, 30) target:self SEL:@selector(enterbtnClick) title:@"进入游戏"];
    enterbtn.backgroundColor = [UIColor clearColor];
    [enterbtn setTitleColor:EDColor_BaseBlue forState:0];
    enterbtn.titleLabel.textAlignment = NSTextAlignmentCenter;
    [enterbtn.titleLabel setFont:[UIFont systemFontOfSize:16]];
    [self.bgSc addSubview:enterbtn];
    
    self.topLab2= [BBControl createLabelWithFrame:CGRectMake(10, enterbtn.bottom+20, kScreenWidth-20, 40) Font:16 Text:@"今日投注"];
    self.topLab2.backgroundColor = [UIColor clearColor];
    self.topLab2.textAlignment = NSTextAlignmentCenter;
    [self.bgSc addSubview:self.topLab2];
   
    
    self.btnsView = [BBControl createViewWithFrame:CGRectMake(0, self.topLab2.bottom+10, kScreenWidth, 200)];
    [self.bgSc addSubview:self.btnsView];

    NSString *str = @"活动时间\n\n2019年07月01日——31日\n\n活动适用平台\n\n所有老虎机平台\n\n活动内容\n\n在浩瀚的EDF游戏世界里，各个精彩绚丽的游戏是否让您眼花缭乱了不知道玩什么？没关系，每天EDF会精心挑选一款玩家喜爱的特色游戏进行推荐，只要玩家在每日特色游戏中投注达到相应的流水，都会获得额外的奖励，最高128元哦！\n每日游戏的奖励每人每日仅可领取一次，且必须在当日完成申请，申请之后1～10分钟系统将自动派发到您的【福利领取中心】，逾期不补。派奖规则如下：";
    NSArray *arr = @[@"活动时间",@"活动适用平台",@"活动内容"];
    NSArray *arr2 = @[];
    EDRichTextLabel * leb01 = [[EDRichTextLabel alloc]initWithFrame:CGRectMake(20, self.btnsView.bottom+20, kScreenWidth-40, 500)];
    leb01.backgroundColor = kRGBColor(245, 245, 245);
    [leb01 rich_TextCofigWith:str blodStrArry:arr colortextArry:arr2];
    [leb01 sizeToFit];
    [self.bgSc addSubview:leb01];
    
    UIView * numBgView = [BBControl createViewWithFrame:CGRectMake(10, leb01.bottom+20, kScreenWidth-20, 280)];
    KViewBorder(numBgView, kRGBColor(90, 90, 90), 1);
    [self.bgSc addSubview:numBgView];
    
    NSArray *dataArry = @[@[@"每日游戏投注",@"每日游戏奖励",],@[@"≥58",@"8发币",],@[@"≥388",@"8元",],@[@"≥888",@"18元",],@[@"≥1888",@"58元",],@[@"≥8888",@"88元",],@[@"≥18888",@"128元",]];
        CGFloat  space = 0;
        CGFloat  btnH = 40;
        for (int i = 0 ; i < dataArry.count; i++) {
            NSInteger index = i % 1;
            NSInteger page = i / 1;
            NSArray * titles=dataArry[i];
            TwoBtnsView*mapBtn =[[NSBundle mainBundle]loadNibNamed:@"TwoBtnsView" owner:self options:nil].lastObject;
            mapBtn.frame = CGRectMake(index * (kScreenWidth-20 ), page  * (40 + space), kScreenWidth-20 , btnH);
            mapBtn.leftLab.text = titles.firstObject;
             mapBtn.rightLab.text = titles.lastObject;
            if (i==dataArry.count-1) {
                mapBtn.rightLab.textColor = EDColor_BaseBlue;
            }

          [numBgView addSubview:mapBtn];
        }

    
    NSString *str22 = @"参加方式\n\n您可以从【个人中心】——【自助服务区】——【每日游戏】中，直接点击游戏图片进入游戏，或者在相应客户端中搜索相应游戏均可。\n当完成规定流水要求后，需回到每日游戏界面 自助申请奖金 ，，一旦申请奖金后，继续投注该游戏将不会再计入本活动。提前申请或者忘记申请，都无法进行人工补派。奖励申请成功后，请在【个人中心】——【福利领取中心】——【红利】中领取\n\n活动规则\n\nEDF壹定发会定期与不定期举办各种优惠活动，在您参与前，您必须完全同意以下规则和履行以下义务：\n1、每日游戏不限投注账户类型，但不同游戏可能会限定电脑网页版或手机网页端 ；\n2、每日游戏需根据投注额自助选择申请相应的奖励，如当日提早申请或忘记申请，均无法通过人工进行补派；\n3、每日游戏奖励需满足15倍流水投注于老虎机平台 (除BBIN) ，投注不计返水。4、本优惠是特别为EDF壹定发在线娱乐玩家而设，如发现任何滥用优惠活动的个人或团体等尝试或进行恶意的欺诈行为，以利用红利为获得利润为目的，公司将对违规帐户进行冻结并索回红利及所有盈利。\n5、此活动必须遵守 EDF壹定发一般规则与条款  (请详细阅读)。EDF壹定发保留在任何时候对本活动的修改、停止及最终解释权。";
    NSArray *arr22 = @[@"参加方式",@"活动规则"];
    NSArray *arr222 = @[@"自助申请奖金",@"电脑网页版或手机网页端",@"除BBIN",];
    EDRichTextLabel * leb02 = [[EDRichTextLabel alloc]initWithFrame:CGRectMake(20, numBgView.bottom+20, kScreenWidth-40, 500)];
    leb02.backgroundColor = kRGBColor(245, 245, 245);
    [leb02 rich_TextCofigWith:str22 blodStrArry:arr22 colortextArry:arr222];
    [leb02 sizeToFit];
    [self.bgSc addSubview:leb02];
    self.bgSc.contentSize = CGSizeMake(kScreenWidth, leb02.bottom+50);

}
-(void)enterbtnClick{
    if (kDictIsEmpty(self.gameInfoDicc)) {
        
        [JMNotifyView showNotify:@"未获取到游戏信息，请刷新重试~" isSuccessful:NO];
        return;
    }
    [self showLoadingAnimation];
    NSString  * game = [[YINetWorkAPIGenerate sharedInstance] APINomark:@"getGameUrl"];
    NSMutableDictionary * diccc = [NSMutableDictionary dictionary];
    [diccc setValue:[self.gameInfoDicc jsonString:@"game_gameid"] forKey:@"gameid"];
     [diccc setValue:[self.gameInfoDicc jsonString:@"game_gamecode"] forKey:@"gamecode"];
     [diccc setValue:[self.gameInfoDicc jsonString:@"game_platid"] forKey:@"plat_id"];
     [diccc setValue:@"online" forKey:@"mode"];
    [[SmileHttpTool sharedInstance] GET :game parameters:diccc origin:YES success:^(NSInteger statusCode, NSString *message, id responseObject){
        [self stopLoadingAnimation];
        NSDictionary * dic = [self objectFromJSONString:responseObject];
        if ([dic[@"statusCode"] isEqual:@"SUCCESS"]) //请求成功
        {
            LLWebViewController * webview = [[LLWebViewController alloc] init];
            webview.urlStr = dic[@"data"];
             webview.isType = 3;
            webview.isShowGame = YES;
            [self.navigationController pushViewController:webview animated:YES];
        }else
        {
            [JMNotifyView showNotify:[dic jsonString:@"message"]  isSuccessful:NO];
        }
        
        
    } failure:^(id responseObject, NSError *error) {
        [self stopLoadingAnimation];
        [WJUnit showMessage:@"请求错误"];
        
    }];
    
}

//    "cur_bet" = 0;
//        "game_gamecode" = "christmas_eve";
//        "game_gameid" = "christmas_eve";
//        "game_name" = "\U5e73\U5b89\U591c";
//        "game_pic" = "c_christmas_eve.png";
//        "game_platid" = c;
//        "gameplat_name" = "PSN\U5e73\U53f0";
//        geid = FsFxIOeRRHuoCbDIVLldnw;


@end
